package com.a.module_map

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.LogUtils
import com.a.lib_base.BaseApp
import com.a.lib_utils.TipUtil
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest


/**
 * CREATE BY 黄炜强
 * 2022/7/26 16:44
 * Desc:后台定位及上传
 * */
class LocationService : Service(), TencentLocationListener {
    companion object {
        /**
         * 当退出这个页面时为false
         * */
//        @JvmStatic
//        var hadNavMap = true
    }


    inner class LocalBinder : Binder() {
        fun getService(): LocationService = this@LocationService
    }

    private val localBinder: LocalBinder = LocalBinder()

    override fun onBind(intent: Intent): IBinder {
        val latitude = intent.getDoubleExtra("latitude", 0.0)
        val longitude = intent.getDoubleExtra("longitude", 0.0)
        val address = intent.getStringExtra("address") ?: "未知"
        useTencentNaviApp(address, latitude, longitude)
        return localBinder
    }


    private lateinit var mLocationManager: TencentLocationManager
    private lateinit var mLocationRequest: TencentLocationRequest
    override fun onCreate() {
        super.onCreate()
        buildNotification()
        mLocationManager = TencentLocationManager.getInstance(BaseApp.getContext())
        mLocationRequest = TencentLocationRequest.create()
        mLocationRequest.interval = 3000
        //设置请求级别
        mLocationRequest.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
        //是否允许使用GPS
        mLocationRequest.isAllowGPS = true
        mLocationManager.requestLocationUpdates(mLocationRequest, this)
        //        mLocationManager.requestSingleFreshLocation(mLocationRequest, this, Looper.myLooper())
    }

    override fun onLocationChanged(p0: TencentLocation?, p1: Int, p2: String?) {
        /**
         *   │ TxLocation{level=3,acceleration=0.0,angularrate=0.0,fakecode=0,sourceProvider=network,
         *   fusionProvider=network,name=汕头市宇翔信息技术有限公司,address=广东省汕头市龙湖区超声科技大厦B座,
         *   provider=network,latitude=23.386616,longitude=116.719805,altitude=0.0,accuracy=15.0,bearing=0.0,
         *   speed=0.0,direction=0.0,rssi=0,gpsQulity=-100,buildid=,floor=1000,cityCode=440507,areaStat=0,nation=中国,
         *   province=广东省,city=汕头市,district=龙湖区,street=科技北一街,streetNo=,town=金霞街道,village=Unknown,time=1658822932103,poilist=[]}
        └────────────────────────────────────────────────────────────────────────────────────────────────────────────────
         * */
        LogUtils.d(p0)
//        if (!hadNavMap)
        p0?.let {
            latitude = it.latitude
            longitude = it.longitude
//                useTencentNaviApp("北京仓", it.latitude, it.longitude, it.latitude + 1, it.longitude + 1)
        }
    }

    var latitude: Double = 0.0
    var longitude: Double = 0.0

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
    }

    //    调用腾讯地图app导航
    fun useTencentNaviApp(toName: String, latitude: Double, longitude: Double) {
        LogUtils.d(toName)
//        hadNavMap = true
        try {
            val uri = Uri.parse(
                "qqmap://map/routeplan?type=drive&to=" + toName +
                        "&fromcoord=" + this.latitude + "," + this.longitude +
                        "&tocoord=" + latitude + "," + longitude + "&referer=XC6BZ-ZSL6Q-SST5Y-G757Y-ERCR3-ZLBKB"
            )
            val intent = Intent()
            intent.data = uri
            this.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            TipUtil.toast("请安装腾讯地图")
        }
    }

    lateinit var notificationManager: NotificationManager
    private fun buildNotification() {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("my_service", "前台服务", NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }

        val intent = Intent(this, TencentMapActivity::class.java)
//        val pi = PendingIntent.getActivity(this, 0, intent, 0)
        val builder = NotificationCompat.Builder(this, "MyService")

        builder.setContentTitle("捷优易")
            .setContentInfo("b物流正在定位")
            .setSmallIcon(R.drawable.nlogo)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.nlogo))
//            .setContentIntent(pi)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("my_service")
        }
//        val notification = builder.build()
//        startForeground(1, notification)

    }

    override fun onUnbind(intent: Intent?): Boolean {
        LogUtils.d("sadas")
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        LogUtils.d("sadas")
        mLocationManager.removeUpdates(this);
        super.onDestroy()
    }
}